package com.gcloud.mesh.dcs.rpc;

import com.gcloud.mesh.dcs.service.VoltageFmService;
import com.gcloud.mesh.grpc.api.RPCReportDvfsRequest;
import com.gcloud.mesh.grpc.api.RPCReportDvfsResponse;
import com.gcloud.mesh.grpc.api.RPCReportDvfsServiceGrpc;
import com.gcloud.mesh.header.msg.dvfs.ReportDvfsMsg;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class RPCReportDvfsService extends RPCReportDvfsServiceGrpc.RPCReportDvfsServiceImplBase {

    @Autowired
    private VoltageFmService voltageFmService;

    @Override
    public void reportDvfs(RPCReportDvfsRequest request, StreamObserver<RPCReportDvfsResponse> responseObserver) {
        ReportDvfsMsg msg = new ReportDvfsMsg();
        msg.setHostname(request.getHostname());
        msg.setDriver(request.getDriver());
        msg.setAvailableStrategy(request.getAvailableStrategy());
        msg.setCurrentFrequency(request.getCurrentFrequency());
        msg.setFrequencyLowerLimit(request.getFrequencyLowerLimit());
        msg.setFrequencyUpperLimit(request.getFrequencyUpperLimit());
        log.info("[RPCReportDvfsService]report dvfs接受到的信息为：{}", msg);
        voltageFmService.syncDvfsByServer(msg);
        RPCReportDvfsResponse reportDvfsResponse = null;
        try {
            reportDvfsResponse = RPCReportDvfsResponse
                    .newBuilder()
                    .setSuccess(true)
                    .build();
        } catch (Exception e) {
            responseObserver.onError(e);
        } finally {
            responseObserver.onNext(reportDvfsResponse);
        }
        responseObserver.onCompleted();
    }
}
